package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class AddressController {
	@Autowired
	private AddressService addressService;
	
	@GetMapping("/address/list")
	public ResultInfo findList() {
		List<Address> addressList = addressService.findList();
		return ResultInfo.success(addressList);
	}
	
	@PostMapping("/address")
	public ResultInfo save(@RequestBody Address address) {
		addressService.save(address);
		return ResultInfo.success(null);
	}
	
	@PutMapping("/address/default")
	public ResultInfo setDefault(@RequestBody Map<String,Long> map) {
		Long id = map.get("id");
		addressService.setDefault(id);
		return ResultInfo.success(null);
	}
	
	@GetMapping("/address/default")
	public ResultInfo getDefaultAddress() {
		Address address = addressService.findDefault();
		if (address == null) {
			return ResultInfo.error("没有默认地址");
		} else {
			return ResultInfo.success(address);
		}
	}
	
	@PutMapping("/address")
	public ResultInfo update(@RequestBody Address address) {
		addressService.update(address);
		return ResultInfo.success(null);
	}
	
	@GetMapping("/address/{id}")
	public ResultInfo findById(@PathVariable("id") String id) {
		Address address =  addressService.finById(id);
		return ResultInfo.success(address);
	}
	@DeleteMapping("/address")
	public ResultInfo delete(@RequestParam("ids") List<String> ids) {
		addressService.delete(ids);
		return ResultInfo.success(null);
	}
}
